package com.cxhome.cxinfox.cxuser;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.cxhome.cxinfox.cxmenu.MenuService;
import com.cxhome.cxinfox.productinfo.ProductInfoService;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.traffic.managent.Constants;
import com.traffic.managent.base.BaseService;
import com.traffic.managent.base.Paginator;
import com.traffic.managent.model.system.Menu;
import com.traffic.managent.model.system.Role;
import com.traffic.managent.model.system.User;
import com.traffic.managent.model.system.UserInfo;
import com.traffic.managent.util.SQLUtils;
import com.traffic.managent.util.SecurityPbkdf2Utils;
import com.traffic.managent.util.StringUtils;
import com.traffic.managent.util.UtilsUtils;

public class UserService extends BaseService {

	private final static Logger log = Logger.getLogger(ProductInfoService.class);
	public static final UserService service = new UserService();

	
	
	/**
	 * 分页查询 sql可以放到xml文件里
	 * 
	 * @param model
	 * @param paginator
	 * @param orderSql
	 * @return
	 */
	public Page<User> paginate(User model, Paginator paginator, String orderSql) {

		SQLUtils sql = new SQLUtils(" from cx_user u " + " left join cx_userinfo ui on u.userinfoids = ui.ids "
				+ " left join cx_department d on u.departmentId = d.ids" + " where 1=1  ");

		// 条件查询
		if (model.getAttrValues().length != 0) {
			sql.whereLike("username", model.getStr("username"));
			sql.whereEquals("status", model.getStr("status"));
		}
		// 排序
		sql.append(orderSql);

		return User.dao.paginate(paginator,
				"select u.ids,u.type, u.username,u.roleids, ui.names, ui.email, ui.mobile, ui.birthday, d.names as deptnames,d.pathsName,u.status ",
				sql.toString());

	}

	
	
	@Before(Tx.class)
	public String saveOrUpdate(User usermodel, UserInfo userinfomodel, String ids, String username) {
		try {
			// 编辑
			if (ids != null && !"".equals(ids)) {

				usermodel.put("departmentnames", usermodel.getStr("departmentnames").trim().replace("|--", ""));
				usermodel.update();
				userinfomodel.update();

			} else { // 新增
				String userinfoids = UtilsUtils.getRandomId(30);
				userinfomodel.put("ids", userinfoids);
				userinfomodel.save();

				usermodel.put("ids", UtilsUtils.getRandomId(30));
				usermodel.put("userinfoids", userinfoids);
				usermodel.put("departmentnames", usermodel.getStr("departmentnames").trim().replace("|--", ""));
				usermodel.put("createTime", new Date());
				usermodel.put("createPerson", username);

				byte[] encryptedPassword = null;
				byte[] salt = null;
				try {
					salt = SecurityPbkdf2Utils.generateSalt();// 密码盐
					encryptedPassword = SecurityPbkdf2Utils.getEncryptedPassword("123456", salt);
				} catch (Exception e) {
					e.printStackTrace();
				}

				usermodel.set("salt", salt);
				usermodel.set("password", encryptedPassword);
				usermodel.set("status", "1");

				usermodel.save();

			}
			// 缓存
			User.dao.cacheAdd(usermodel.getStr("ids"));

		} catch (Exception e) {
			return Constants.OPER_FAIL;
		}
		return Constants.OPER_SUCCESS;

	}

	public void delete(String userIds) {
		try {
			User user = User.dao.findById(userIds);
			// 1 删除缓存
			User.dao.cacheRemove(userIds);
			// 2 逻辑删除
			user.set("status", "0");// 0为停用
			user.update();
		} catch (Exception e) {

		}
	}

	/**
	 * 返回菜单权限
	 */
	public Map<String, List<Menu>> getAuthMap(User user) {

		Map<String, List<Menu>> map = new HashMap<String, List<Menu>>();

		// 获取根目录
		List<Menu> rootList = MenuService.service.getMenuListByParentid(user);

		if (rootList == null || rootList.size() == 0) {
			return null;
		}

		// 获取用户operatorID
		// 根据userid 获取roleids
		String roleids = user.getStr("roleids");
		String[] roleidsArr = roleids.split(",");
		String roleidsstr = "";
		for (int i = 0; i < roleidsArr.length; i++) {
			roleidsstr += "'" + roleidsArr[i] + "',";
		}
		roleidsstr = roleidsstr.substring(0, roleidsstr.length() - 1);
		// 查询角色
		List<Role> listrole = Role.dao.find("select * from cx_role where 1=1 and ids in (" + roleidsstr + ")");

		// 查询角色拥有的菜单operatorids
		String useroperatorids = "";
		String useroperArrStr = "";
		for (int i = 0; i < listrole.size(); i++) {
			useroperatorids += listrole.get(i).getStr("operatorids");
		}

		if (useroperatorids != null && !"".equals(useroperatorids)) {
			String[] useroperArr = useroperatorids.split(",");
			for (int i = 0; i < useroperArr.length; i++) {
				useroperArrStr += "'" + useroperArr[i] + "',";
			}
			useroperArrStr = useroperArrStr.substring(0, useroperArrStr.length() - 1);
		}
		useroperArrStr = useroperArrStr.replaceAll("operator_", "");

		List<Menu> romelist = new ArrayList<Menu>();
		// 获取子目录
		for (Menu sysMenu : rootList) {
			// 暂时使用m.url,应该是o.url
			String sql = " SELECT m.ids,m.names_zhcn, o.url FROM cx_menu m LEFT JOIN cx_operator o ON m.operatorids = o.ids WHERE parentmenuids = '"
					+ sysMenu.getStr("ids") + "' AND m.operatorids IN (" + useroperArrStr + ") ";
			List<Menu> list = Menu.dao.find(sql);
			if (list != null && list.size() > 0) {
				map.put(sysMenu.getStr("ids"), list);
			} else {
				romelist.add(sysMenu);
			}
		}
		rootList.removeAll(romelist);
		// for (CxMenu sysMenu : rootList) {
		// //暂时使用m.url,应该是o.url
		// String sql = " SELECT m.names_zhcn, m.url FROM cx_menu m LEFT JOIN
		// cx_operator o ON m.operatorids = o.ids WHERE parentmenuids =
		// '"+sysMenu.getStr("ids")+"' AND m.operatorids IN ("+useroperArrStr+")
		// ";
		// List<CxMenu> list = CxMenu.dao.find(sql);
		// if(list !=null && list.size()>0){
		// map.put(sysMenu.getStr("ids"), list);
		// }else{
		// rootList.remove(sysMenu);
		// }
		// }
		map.put("0", rootList);

		return map;
	}
	// public Map<String, List<CxMenu>> getAuthMap(CxUser user) {
	//
	// Map<String, List<CxMenu>> map = new HashMap<String, List<CxMenu>>();
	//
	// // 获取根目录
	// List<CxMenu> rootList =
	// CxMenuService.service.getMenuListByParentid(user);
	//
	// if (rootList == null || rootList.size() == 0) {
	// return null;
	// }
	//
	// map.put("0", rootList);
	//
	// String sql = " where 1=1 and parentmenuids = ? ";
	// // 获取子目录
	// for (CxMenu sysMenu : rootList) {
	// List<CxMenu> list = CxMenu.dao.findByWhere(sql, sysMenu.getStr("ids"));
	// map.put(sysMenu.getStr("ids"), list);
	// }
	//
	// return map;
	// }

	/**
	 * 获取没有权限的菜单
	 * 
	 */
	public List<Menu> getNoAuthMap(Map<String, List<Menu>> map) {

		List<Menu> list = Menu.dao.findByWhere(" where 1=1");

		List<Menu> returnList = new ArrayList<Menu>();

		// 封装
		List<String> idList = new ArrayList<String>();

		for (String key : map.keySet()) {
			List<Menu> childList = map.get(key);
			for (Menu sysMenu : childList) {
				idList.add(sysMenu.getStr("ids"));
			}
			idList.add(key);
		}

		for (Menu sysMenu : list) {
			if (!idList.contains(sysMenu.getStr("ids"))) {
				returnList.add(sysMenu);
			}
		}

		return returnList;
	}
	// public List<CxMenu> getNoAuthMap(Map<String, List<CxMenu>> map) {
	//
	// List<CxMenu> list = CxMenu.dao.findByWhere(" where 1=1");
	//
	// List<CxMenu> returnList = new ArrayList<CxMenu>();
	//
	// //封装
	// List<String> idList = new ArrayList<String>();
	//
	// for (String key : map.keySet()) {
	// List<CxMenu> childList = map.get(key);
	// for (CxMenu sysMenu : childList) {
	// idList.add(sysMenu.getStr("ids"));
	// }
	// idList.add(key);
	// }
	//
	// for (CxMenu sysMenu : list) {
	// if (!idList.contains(sysMenu.getStr("ids"))) {
	// returnList.add(sysMenu);
	// }
	// }
	//
	// return returnList;
	// }

	/**
	 * 获取用户绑定的角色
	 * 
	 */
	public String getRoleids(String userids) {
		String sql = " select group_concat(roleids) as roleids from cx_user where ids = ?";
		Record record = Db.findFirst(sql, userids);
		String roleids = record.getStr("roleids");
		return roleids;
	}

	/**
	 * 保存用户授权信息
	 * 
	 */
	public void saveAuth(String userid, String roleids, String update_id) {

		if (StringUtils.isNotEmpty(roleids)) {
			Db.update("UPDATE cx_user SET roleids = ? WHERE ids = ?", roleids, userid);
			User.dao.cacheAdd(userid);
		}
	}

}
